#!/bin/bash
# 一键切换 Debian 国内源
# 适用于 Debian 10/11/12，自动识别 codename（buster, bullseye, bookworm）

set -e

# 获取当前 Debian codename
CODENAME=$(lsb_release -sc 2>/dev/null || grep VERSION_CODENAME /etc/os-release | cut -d= -f2)

if [ -z "$CODENAME" ]; then
  echo "❌ 无法检测到 Debian 版本代号，请手动确认。"
  exit 1
fi

echo "当前 Debian 版本代号: $CODENAME"

# 备份源文件
BACKUP_FILE="/etc/apt/sources.list.bak.$(date +%Y%m%d%H%M%S)"
sudo cp /etc/apt/sources.list $BACKUP_FILE
echo "已备份原始 sources.list 到 $BACKUP_FILE"

# 提供可选源
echo "请选择要使用的镜像源:"
echo "1) 中科大 (USTC)"
echo "2) 清华大学 (TUNA)"
echo "3) 阿里云 (Aliyun)"
read -p "输入序号 [1-3]: " choice

case $choice in
  1)
    MIRROR="https://mirrors.ustc.edu.cn/debian"
    ;;
  2)
    MIRROR="https://mirrors.tuna.tsinghua.edu.cn/debian"
    ;;
  3)
    MIRROR="http://mirrors.aliyun.com/debian"
    ;;
  *)
    echo "❌ 无效的选择"
    exit 1
    ;;
esac

# 写入新的源配置
sudo tee /etc/apt/sources.list > /dev/null <<EOF
deb $MIRROR $CODENAME main contrib non-free non-free-firmware
deb $MIRROR $CODENAME-updates main contrib non-free non-free-firmware
deb $MIRROR $CODENAME-backports main contrib non-free non-free-firmware
deb $MIRROR-security $CODENAME-security main contrib non-free non-free-firmware
EOF

echo "✅ 已切换到 $MIRROR"

# 更新软件包索引
sudo apt update
